#!/usr/bin/env python
# -*- coding: utf-8 -*-

import vk
import os
import re

from optparse import OptionParser
usage = """usage: %prog [options] <album URL> [<file and dir names>]
If no file and dir name are given, the current dir will be used as a picture dir
"""
parser = OptionParser(usage=usage)
parser.add_option("-a", "--auth", dest="auth",
                  help="specify user login and password as <login>:<password>")
try:
    options, args = parser.parse_args(os.sys.argv)
    args = args[1:]
    if len(args) < 1:
        raise Exception('lol')
except Exception as e:
    parser.parse_args([os.sys.argv[0], '-h'])
    os.sys.exit(-1)
if options.auth:
    try:
        login,password = options.auth.split(':')
    except Exception as e:
        parser.parse_args([os.sys.argv[0], '-h'])
        os.sys.exit(-1)
else:
    login, password = vk.get_static_auth()

session = vk.Vkontakte(login, password)

album_url = args[0]
oid, aid = album_url.split('album')[1].split('_')

lst = map(os.path.abspath,args[1:]) or os.path.abspath(os.curdir)

for f in lst:
    if os.path.isdir(f):
        l = os.listdir(f)
        l = [os.path.join(f,i) for i in l]
    else:
        l = [f]
    for fn in l:
        fname = os.path.abspath(fn)
        if re.match(r'.*\.(jpg|png|gif)', fname, re.IGNORECASE):
            print 'Uploading', fn
            upload_data = session.picture_upload_data(aid, oid)
            session.picture_upload_file(upload_data, fname)
